package com.example.chatchatbackend.handler;

import com.example.chatchatbackend.entity.vo.request.AdvVO;
import com.example.chatchatbackend.entity.vo.response.SendAdvVO;
import com.example.chatchatbackend.service.AdvService;
import com.example.chatchatbackend.service.sendJob.SendAdvService;
import com.example.chatchatbackend.utils.TimeUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class AdvHandler {

    @Resource
    private AdvService advService; // 假设有一个服务类用于处理数据库操作

    @Resource
    private SendAdvService sendAdvService;

    private static final LocalDateTime currentTime = TimeUtil.Time_Now.getCurrentTime();

    @XxlJob("advTaskHandler")
    public void execute() {

        XxlJobHelper.log("Xxl-Job:Insert");

        // 查询发送时间小于当前时间且未发送的任务
        List<SendAdvVO> tasksToSend = sendAdvService.findTasksToSend(this.currentTime);
        if(tasksToSend.isEmpty()){
            XxlJobHelper.log("无需更新，所有记录已发送");
            return;
        }

        SendAdvVO sendAdvVO = tasksToSend.get(0);

        AdvVO advVO = new AdvVO();
        BeanUtils.copyProperties(sendAdvVO, advVO);

        advService.insertAdv(advVO);
        sendAdvService.updateIsSend(sendAdvVO);
        XxlJobHelper.log("成功插入Adv：{}",advVO);


    }
}
